import json
import os

CONFIG_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "tool_config.json"))

def configure_tool_status(tool_name: str = None, band_all: bool = None, enable: bool = True) -> dict:
    """配置工具的启用状态，修改 tool_config.json 文件。

    可以禁用或启用单个工具，或一次性操作所有工具（除本工具外）。
    本工具 (configure_tool_status) 不可被禁用。

    Args:
        tool_name (str, optional): 要配置的工具名称。默认为 None。
        band_all (bool, optional): 设置为 True 禁用所有工具，False 启用所有工具。默认为 None。
        enable (bool, optional): 设置为 True 启用工具，False 禁用。默认为 True。

    Returns:
        dict: 返回操作状态的字典。
    """
    try:
        with open(CONFIG_PATH, 'r+', encoding='utf-8') as f:
            config = json.load(f)

        if band_all is not None:
            config["band_all"] = band_all
            action = "banned" if band_all else "unbanned"
            message = f"All tools have been {action}."

        if tool_name:
            # Prevent this tool from being disabled
            if tool_name == "configure_tool_status":
                return {"status": "failure", "message": "This tool cannot be disabled."}

            if enable:
                if tool_name in config["disabled_tools"]:
                    config["disabled_tools"].remove(tool_name)
                    message = f"Tool '{tool_name}' has been enabled."
                else:
                    message = f"Tool '{tool_name}' is already enabled."
            else: # disable
                if tool_name not in config["disabled_tools"]:
                    config["disabled_tools"].append(tool_name)
                    message = f"Tool '{tool_name}' has been disabled."
                else:
                    message = f"Tool '{tool_name}' is already disabled."

        with open(CONFIG_PATH, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2)

        return {"status": "success", "message": message}

    except FileNotFoundError:
        return {"status": "failure", "message": "tool_config.json not found."}
    except Exception as e:
        return {"status": "failure", "message": str(e)}
